import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/home_announcement_mdoel.dart';
import 'package:flutter_syt/domain/widgets/stupid_tabs.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/global_date_time_format.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "announcements_page")
class HomeAnnouncementsPage extends StatefulWidget {
  @override
  HomeAnnouncementsPageState createState() => HomeAnnouncementsPageState();
}

class HomeAnnouncementsPageState extends State<HomeAnnouncementsPage>
    with TickerProviderStateMixin {
  List<ScrollerTabEntity> types = [];
  late Future<List<ScrollerTabEntity>> _future;
  TabController? _tabController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            S.of(context).home_announcement,
            style: FontStyles.headerTextStyle_18.copyWith(
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        body: FutureBuilder<List<ScrollerTabEntity>>(
            future: _future,
            builder: (ctx, AsyncSnapshot<List<ScrollerTabEntity>> snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Container();

              } else if (!snapshot.hasData || snapshot.data == null) {
                return Container(
                  width: double.infinity,
                  height: double.infinity,
                  child: Center(
                    // ViewStateEmptyWidget

                    child: ViewStateErrorWidget(),
                  ),
                );
              } else if ((snapshot.data ?? []).isEmpty) {
                return Container(
                  width: double.infinity,
                  height: double.infinity,
                  child: Center(
                    // ViewStateEmptyWidget
                    child: ViewStateEmptyWidget(),
                  ),
                );
              }
              var list = snapshot.data!;
              List<ScrollerTabEntity> tabList = [];
              List<Widget> pageList = [];
              for (int idx = 0; idx < list.length; idx++) {
                ScrollerTabEntity element = list[idx];
                Widget? page = HomeAnnounItemPage(id: element.id ?? '');
                pageList.add(page);
                tabList.add(element);
              }
              // var temp =
              //     ScrollerTabEntity.create('eye_list', S.of(context).live_2, 1, '');
              // tabList.add(temp);
              // var live = GameLiveSinglePage();
              // live.needBar = false;
              // pageList.add(live);
              if (_tabController == null ||
                  _tabController?.length != list.length) {
                _tabController = TabController(
                    initialIndex: 0, length: tabList.length, vsync: this);
              }
              // NormalTabs(
              //               tabList,
              //               _tabController!,
              //               textColor: Colors.black,
              //               alignment: Alignment.centerLeft,
              //             ),
              return Column(
                children: [
                  NormalTabs(
                    tabList,
                    _tabController!,
                    textColor: Colors.black,
                    // alignment: Alignment.centerLeft,
                  ),
                  Container(
                    height: 0.5,
                    color: Colors.black.withOpacity(0.1),
                  ),
                  Expanded(
                    child: TabBarView(
                      controller: _tabController,
                      children: pageList,
                    ),
                  ),
                ],
              );
            }));
  }

// await API.shared.common.getHomeAnnouncement();
  Future<List<ScrollerTabEntity>> loadCategory() async {
    types = await API.shared.common.getAnnouncementTabs();
    return types;
    // yield types
    //     .map((e) => ScrollerTabEntity.create(
    //           e.showType,
    //           e.name,
    //           parseInt(e.showType),
    //           e.alias,
    //         ))
    //     .toList();
  }

  @override
  void initState() {
    super.initState();
    _future = loadCategory();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(HomeAnnouncementsPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class HomeAnnounItemPage extends StatefulWidget {
  final String id;

  HomeAnnounItemPage({required this.id});

  @override
  HomeAnnounItemPageState createState() => HomeAnnounItemPageState();
}

class HomeAnnounItemPageState extends State<HomeAnnounItemPage> {
  NormalTableViewController controller = NormalTableViewController();

  @override
  Widget build(BuildContext context) {
    return NormalTableView<HomeAnnouncementMdoel>(
      controller: controller,
      itemBuilder: (context, item) {
        DLog(item.toJson());
        return GestureDetector(
          // child: FlowItem(item),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                    padding: EdgeInsets.only(top: 19.w, bottom: 6.w),
                    child: Text(
                      item.title ?? '',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 16,
                          fontWeight: FontWeight.bold),
                    )),
                Visibility(
                    child: RichText(
                        text: TextSpan(children: [
                  TextSpan(
                    text: item.author ?? '',
                    style: TextStyle(
                      color: Colors.black.withOpacity(0.4),
                      fontSize: 12,
                    ),
                  ),
                  WidgetSpan(
                      child: Visibility(
                          visible: (item.author ?? '').length > 0,
                          child: SizedBox(
                            width: 16.w,
                          ))),
                  TextSpan(
                    text: calculateYearMonthDay(item.publishTime ?? 0),
                    style: TextStyle(
                      color: Colors.black.withOpacity(0.4),
                      fontSize: 12,
                    ),
                  )
                ]))),
                // Text(
                //   (item.content ?? '')
                //       .replaceAll('<p>', '')
                //       .replaceAll("</p>", ''),
                //   maxLines: 2,
                //   overflow: TextOverflow.ellipsis,
                //   style: TextStyle(
                //     color: Colors.black.withOpacity(0.6),
                //     fontSize: 14,
                //   ),
                // ),
                SizedBox(
                  height: 20.w,
                ),
                Container(
                  height: 0.5,
                  color: Colors.black.withOpacity(0.1),
                )
              ],
            ),
          ),
          behavior: HitTestBehavior.opaque,
          onTap: ClickUtils.debounce(() {
            DLog(item.type);
            UtilsOther.clickAnnouncementJump(item, context);
            // RouteManager.push(context, item.newsUrl ?? '');
          }),
        );
      },
      getData: (pageNumber) async {
        List<HomeAnnouncementMdoel> lists =
            await API.shared.common.getHomeAnnouncement(id: widget.id);
        DLog(lists);
        return lists;
      },
    );
  }

  String calculateYearMonthDay(int createtime) {
    // (appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale()).contains('zh');
    return (appContext.storage.getString("storyLocal") ??
                    Intl.getCurrentLocale())
                .contains('zh') ==
            true
        ? formatDate(createtime)
        : enFormatDate(createtime);
    // DateTime? dateTime = DateTime.tryParse((createtime).toString());
    // return DateUtil.formatDate(dateTime, format: 'yyyy-MM-dd');
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(HomeAnnounItemPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
